package org.artifact.core.plugin.netty.handler;

import org.artifact.core.context.packet.IPacket;
import org.artifact.core.context.session.ISession;
import org.artifact.core.lang.IServer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
@SuppressWarnings("unchecked")
public class NettyHandler extends ChannelInboundHandlerAdapter {

	public static final AttributeKey<ISession> SESSION = AttributeKey.valueOf("session");

	public static final AttributeKey<int[]> DECRYPTION_KEYS_ATTRIBUTE_KEY = AttributeKey.valueOf("decryptionKeys");
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		// 创建session
		Attribute<ISession> session = ctx.channel().attr(SESSION);
		session.set(IServer.me().getContext().getSessionFactory().createSession(ctx.channel()));
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		super.channelRead(ctx, msg);
		Attribute<ISession> session = ctx.channel().attr(SESSION);
		ISession isession = session.get();
		if (isession != null) {
			if (msg instanceof IPacket) {
				IPacket packet = (IPacket) msg;
				System.out.println(packet.getBody());
				
				ctx.channel().writeAndFlush(packet);
				
				isession.receivePacket(packet);
			}
		}
	}

	
	
}
